package com.atguigu.lease.web.app.service.impl;




import com.google.gson.Gson;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Service
public class DeepSeekClient {
    private static  String API_KEY;
    private static  String API_URL;

    static {
        Properties properties = new Properties();
        try {

            InputStream is = DeepSeekClient.class.getResourceAsStream("/application.properties");
            properties.load(is);
            API_KEY = properties.getProperty("key");
            API_URL = properties.getProperty("url");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public String ask(String content){
        // 创建消息列表
        List<DeepSeekClient.Message> messages = new ArrayList<>();
        messages.add(new DeepSeekClient.Message("system", "你是租好房项目中的一名智能AI助手，擅长解答用户关于租房、房源图片、地理位置、价格、推荐等问题。你的回答要专业、简洁、有礼貌。"));
        messages.add(new DeepSeekClient.Message("user", content));

        // 构建请求体
        DeepSeekClient.ChatRequest requestBody = new DeepSeekClient.ChatRequest(
                "deepseek-chat",  // 模型名称，根据文档调整
                messages,
                0.7,  // temperature
                1000  // max_tokens
        );
        System.out.println(">>>正在提交问题...");
        long startTime = System.currentTimeMillis();
        // 发送请求
        String response = sendRequest(requestBody);
        long endTime = System.currentTimeMillis();
        System.out.println("思考用时："+(endTime-startTime)/1000+"秒");
//        System.out.println("响应内容: " + response);
    //    PrintWord.printWord(response,20);
            return response;
    }

    private static String sendRequest(DeepSeekClient.ChatRequest requestBody) {
        HttpClient client = HttpClient.newHttpClient();
        Gson gson = new Gson();
        //将 ChatRequest 对象中封装的数据转为 JSON 格式
        String requestBodyJson = gson.toJson(requestBody);

//        System.out.println("请求体：");
//        System.out.println(requestBodyJson);

        try {
            //构建请求对象 并指定请求头内容格式及身份验证的key
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(API_URL))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + API_KEY)
                    //将JSON格式的字符串封装为 BodyPublishers 对象
                    .POST(HttpRequest.BodyPublishers.ofString(requestBodyJson))
                    .build();  //构建请求对象

            System.out.println(">>>已提交问题，正在思考中....");
            // 发送请求并获取响应对象
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            //如果响应状态码为成功 200
            if (response.statusCode() == 200) {
//                System.out.println("响应体：");
//                System.out.println(response.body());
                // 解析响应 把响应体中的json字符串转为 ChatResponse 对象
                DeepSeekClient.ChatResponse chatResponse = gson.fromJson(response.body(), DeepSeekClient.ChatResponse.class);
                //按 JSON 格式的方式 从自定义的ChatResponse 对象中逐级取出最终的响应对象
                String originalContent = chatResponse.getChoices().get(0).getMessage().getContent();
                String modifiedContent = "[租好房AI助手]\n" + originalContent;
                return modifiedContent;
            } else {
                return "请求失败，状态码: " + response.statusCode() + ", 响应: " + response.body();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }

    // 内部类定义请求/响应结构
    static class Message {
        private String role;
        private String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }

        public String getContent() {
            return content;
        }
    }

    /**
     * 请求体的数据内部结构，用于构建请求 JSON
     */
    static class ChatRequest {
        private String model;
        private List<DeepSeekClient.Message> messages;
        private double temperature;
        private int max_tokens;

        public ChatRequest(String model, List<DeepSeekClient.Message> messages, double temperature, int max_tokens) {
            this.model = model;
            this.messages = messages;
            this.temperature = temperature;
            this.max_tokens = max_tokens;
        }
    }


    /**
     * 按着响应的JSON格式来设计响应体
     * 用来封装响应体字符串
     */
    static class ChatResponse {
        private List<DeepSeekClient.ChatResponse.Choice> choices;

        public List<DeepSeekClient.ChatResponse.Choice> getChoices() {
            return choices;
        }

        static class Choice {
            private DeepSeekClient.Message message;

            public DeepSeekClient.Message getMessage() {
                return message;
            }
        }
    }
}
